package com.zjdiepu.www.biz.partner;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.diepu.www.client.xhh.partner.request.ApplyLastInstanceRequest;
import com.diepu.www.client.xhh.partner.request.ApplyLoanRequest;
import com.diepu.www.client.xhh.partner.request.QueryStatusRequest;
import com.diepu.www.client.xhh.partner.response.ApplyLoanResponse;
import com.diepu.www.client.xhh.partner.response.ApproveMessage;
import com.diepu.www.client.xhh.partner.response.BasePartnerResponse;
import com.diepu.www.client.xhh.partner.response.QueryApproveResponse;
import com.diepu.www.client.xhh.partner.response.QueryRepayResponse;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.AddedStatus1;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.ThirdApproveStatus;
import com.zjdiepu.www.base.enums.status.ThirdBusiStatus;
import com.zjdiepu.www.base.enums.status.ThirdCompensatoryStatus;
import com.zjdiepu.www.base.enums.status.ThirdHandleStatus;
import com.zjdiepu.www.base.enums.status.ThirdLogEventStatus;
import com.zjdiepu.www.base.enums.type.ClientType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.ThirdModeIDType;
import com.zjdiepu.www.biz.helper.ServiceHelper;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.helper.UserMapSalermanHelper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessDetailMapper;
import com.zjdiepu.www.consts.XhhService;
import com.zjdiepu.www.dao.partner.ThYwBusinessMapper;
import com.zjdiepu.www.dao.yw.YwBusinessBuyerMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.dao.zpp.PublicDao;
import com.zjdiepu.www.ibiz.fk.IFkAuditListService;
import com.zjdiepu.www.ibiz.partner.IThAuditinfoService;
import com.zjdiepu.www.ibiz.partner.IThBusinessRecordService;
import com.zjdiepu.www.ibiz.partner.IThCreditResultService;
import com.zjdiepu.www.ibiz.partner.IThHandleErrService;
import com.zjdiepu.www.ibiz.partner.IThInsteadPayListService;
import com.zjdiepu.www.ibiz.partner.IThLogsService;
import com.zjdiepu.www.ibiz.partner.IThYwBusinessRequestService;
import com.zjdiepu.www.ibiz.partner.IThYwBusinessService;
import com.zjdiepu.www.ibiz.third.IJuheCarService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.model.fk.dto.FkAuditList;
import com.zjdiepu.www.model.partner.dto.ThAuditinfo;
import com.zjdiepu.www.model.partner.dto.ThInsteadPayList;
import com.zjdiepu.www.model.partner.dto.ThYwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.zpp.pub.ext.WhereSqlExt;
import com.zjdiepu.www.security.exception.BasePartnerException;
import com.zjdiepu.www.util.CachedEnums;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.xhh.XinHeHuiClient;

/**
 * Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年09月21日 10时04分<br/>
 * @since 1.0<br/>
 */
@Service
public class ThYwBusinessRequestServiceImpl extends BaseService implements IThYwBusinessRequestService {
	public static final Logger logger = LoggerFactory.getLogger(ThYwBusinessRequestServiceImpl.class);

	@Autowired
	private IThYwBusinessService thYwBusinessService;
	@Autowired
	private IThAuditinfoService thAuditinfoService;
	@Autowired
	private IThHandleErrService thHandleErrService;
	@Autowired
	private ServiceHelper serviceHelper;
	@Autowired
	private IThLogsService thLogsService;
	@Autowired
	private IJuheCarService juheCarService;
	@Autowired
	private YwBusinessBuyerMapper ywBusinessBuyerMapper;
	@Autowired
	private ThYwBusinessMapper thYwBusinessMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private UserMapSalermanHelper userMapSalermanHelper;
	@Autowired
	private YwBusinessDetailMapper ywBusinessDetailMapper;
	@Autowired
	private IThBusinessRecordService thBusinessRecordService;
	@Autowired
	private IThCreditResultService thCreditResultService;
	@Autowired
	private IThInsteadPayListService thInsteadPayListService;
	@Autowired
	private IFkAuditListService fkAuditListService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private PublicDao publicDao;
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public boolean saveApplyXinHeHuiLoan(String busiId, String currentUserId, String currentUserName) {
		if(StringUtils.isBlank(busiId)) { //业务ID无，不需要记录错误处理（没意义）
			ExceptionHelper.thow("999", "业务记录ID不能为空");
		}
		Date now = new Date();
		YwBusinessDetail ywBusinessDetail = null;
		String salermanProvince = null;
		ApplyLoanRequest applyLoanRequest = null;
		String xeApplyNo = null;
		
		String preRequestUrl = null;
		Map<String, String> preRequestParam = null;
		
		String busiType = "xhh";
		try {
			applyLoanRequest = new ApplyLoanRequest();
			
			ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(busiId);
			if(null == ywBusinessDetail) {
				ExceptionHelper.thow("999", "业务记录不存在或已被删除");
			}
			ywBusinessDetailMapper.mapper(ywBusinessDetail);
			
			String salesmanId = ywBusinessDetail.getSalesmanId();
			if(StringUtils.isBlank(salesmanId)) {
				ExceptionHelper.thow("999", "业务员ID不能为空");
			}
			salermanProvince = userMapSalermanHelper.getSalermanProvinceBySalesmanId(salesmanId);
			if(StringUtils.isBlank(salermanProvince)) {
				ExceptionHelper.thow("999", "业务员所属省份编码为空");
			}
			applyLoanRequest.setSalesmanProvince(salermanProvince);
			
			YwBusinessBuyer ywBusinessBuyerParam = new YwBusinessBuyer();
			ywBusinessBuyerParam.setBusiId(busiId);
			ywBusinessBuyerParam.setCarManType("03"); //主借人
			ywBusinessBuyerParam.setDpStatus(DpStatus.NORMAL.getCode());
			YwBusinessBuyer zhuJieRen = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
			if(null == zhuJieRen) {
				ExceptionHelper.thow("999", "主借人记录不存在或已被删除");
			}
			applyLoanRequest.setName(zhuJieRen.getName());
			applyLoanRequest.setCardNo(zhuJieRen.getIdno());
			applyLoanRequest.setMobile1(zhuJieRen.getTel1());
			
			ywBusinessBuyerParam.setCarManType("01");//配偶
			YwBusinessBuyer peiou = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
			if(null != peiou) {
				applyLoanRequest.setSpouseName(peiou.getName());
				applyLoanRequest.setSpouseCardNo(peiou.getIdno());
				applyLoanRequest.setSpouseMobile(peiou.getTel1());
			}
			
			preRequestUrl = XinHeHuiClient.preRequestUrl(XhhService.APPLY_LOAN);
			preRequestParam = XinHeHuiClient.preRequestParam(applyLoanRequest);
		} catch (Exception e) {
			String[] ids = saveThBussinessAndLog(busiType, busiId, ywBusinessDetail, ThirdBusiStatus.WU, ThirdCompensatoryStatus.WEI_DAI_CHANG, 
					ClientType.PC, applyLoanRequest, null, ThirdLogEventStatus.FAIL, XhhService.APPLY_LOAN_DES, ThirdModeIDType.TJCS,
					xeApplyNo, salermanProvince, currentUserId, currentUserName);
			
			String dataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, dataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FA_SONG_SHI_BAI, null, ThirdModeIDType.TJCS, 
					currentUserId, currentUserName, now);
			return false;
		}
//		==========================请求前:开始==================================
//		======================请求:开始===========================
		String requestJsonString = null;
		try {
			requestJsonString = XinHeHuiClient.request(preRequestUrl, preRequestParam);
		} catch (Exception e) {
			String[] ids = saveThBussinessAndLog(busiType, busiId, ywBusinessDetail, ThirdBusiStatus.WU, ThirdCompensatoryStatus.WEI_DAI_CHANG, 
					ClientType.PC, applyLoanRequest, requestJsonString, ThirdLogEventStatus.FAIL, XhhService.APPLY_LOAN_DES, ThirdModeIDType.TJCS,
					xeApplyNo, salermanProvince, currentUserId, currentUserName);
			
			String dataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, dataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FAN_HUI_SHI_BAI, null, ThirdModeIDType.TJCS,
					 currentUserId, currentUserName, now);
			return false;
		}
//		======================请求:结束===========================
//		======================处理:开始===========================
		ApplyLoanResponse applyLoanResponse = null;
		try{
			applyLoanResponse = XinHeHuiClient.parseResponse(requestJsonString, ApplyLoanResponse.class);
			if(null == applyLoanResponse || StringUtils.isBlank(applyLoanResponse.getXeApplyNo())) {
				throw new BasePartnerException(999, "返回的数据或申请编号为空");
			}
			xeApplyNo = applyLoanResponse.getXeApplyNo();
			String[] ids = saveThBussinessAndLog(busiType, busiId, ywBusinessDetail, ThirdBusiStatus.CHU_SHEN_ZHONG, ThirdCompensatoryStatus.WEI_DAI_CHANG, 
					ClientType.PC, applyLoanRequest, requestJsonString, ThirdLogEventStatus.SUCCESS, XhhService.APPLY_LOAN_DES, ThirdModeIDType.TJCS,
					xeApplyNo, salermanProvince, currentUserId, currentUserName);
			
			String dataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, dataId, busiType, xeApplyNo, 
					XhhService.APPLY_LOAN_DES, ThirdModeIDType.TJCS, currentUserId, currentUserName);
			
			YwBusiness ywBusiness= new YwBusiness();
			ywBusiness.setId(busiId);
			ywBusiness.setThirdBusiStatus(ThirdBusiStatus.CHU_SHEN_ZHONG.getCode());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			return true;
		} catch (Exception e) {
			String[] ids = saveThBussinessAndLog(busiType, busiId, ywBusinessDetail, ThirdBusiStatus.CHU_SHEN_ZHONG, ThirdCompensatoryStatus.WEI_DAI_CHANG, 
					ClientType.PC, applyLoanRequest, requestJsonString, ThirdLogEventStatus.FAIL, XhhService.APPLY_LOAN_DES, ThirdModeIDType.TJCS,
					xeApplyNo, salermanProvince, currentUserId, currentUserName);
			
			String dataId = (null != ids && ids.length > 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, dataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.CHU_LI_SHI_BAI, null, ThirdModeIDType.TJCS,
					currentUserId, currentUserName, now);
			return false;
		}
//		======================处理:结束===========================		
	}
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public boolean saveQueryXinHeHuiStatus(String busiId, int queryType,
			String currentUserId, String currentUserName) {
		if(StringUtils.isBlank(busiId)) { //业务ID无，不需要记录错误处理（没意义）
			ExceptionHelper.thow("999", "业务记录ID不能为空");
		}
		Date now = new Date();
		Integer approveStatus = null;
		String approveStatusName = null;
		Date timeAudit = null;
		String customerName = null;
		String salesmanId = null;
		QueryStatusRequest queryStatusRequest = null;
		String xeApplyNo = null;
		String preRequestUrl = null;
		Map<String, String> preRequestParam = null;
		
		String busiType = "xhh";
		String thBusiDataId = null;
		ThirdModeIDType thModeIDType = null;
		String typeMsgEvent = null;
		
		YwBusinessDetail ywBusiness = null;
		ThYwBusiness thYwBusiness = null;
		
		boolean logChuShen = false;
		boolean logZhongShen = false;
		try {
			if(queryType == 1) {
				thModeIDType = ThirdModeIDType.CSCX;
				typeMsgEvent = "28";
			} else if(queryType == 2){
				logChuShen = true;
				thModeIDType = ThirdModeIDType.ZHCX;
				typeMsgEvent = "29";
			} else if(queryType == 3) {
				logChuShen = true;
				logZhongShen = true;
				thModeIDType = ThirdModeIDType.FXSPCX;
				typeMsgEvent = "30";
			} else {
				ExceptionHelper.thow("999", "查询模块参数错误");
			}
			
			queryStatusRequest = new QueryStatusRequest();
			ywBusiness = ywBusinessMapper.selectMultiByPrimaryKey(busiId);
			if(null == ywBusiness) {
				ExceptionHelper.thow("999", "业务记录不存在或已被删除");
			}
			customerName = ywBusiness.getCustomerName();
			salesmanId = ywBusiness.getSalesmanId();
			if(StringUtils.isBlank(salesmanId)) {
				ExceptionHelper.thow("999", "业务员ID不能为空");
			}
			ThYwBusiness thYwBusinessParam = new ThYwBusiness();
			thYwBusinessParam.setBusiType(busiType);
			thYwBusinessParam.setDpStatus(DpStatus.NORMAL.getCode());
			thYwBusinessParam.setBusiId(busiId);
			thYwBusiness = thYwBusinessMapper.selectRefined(thYwBusinessParam);
			if(null == thYwBusiness) {
				ExceptionHelper.thow("9999", "第三方订单信息记录不存在或已被删除");
			}
			thBusiDataId = thYwBusiness.getId();
			xeApplyNo = thYwBusiness.getThirdId();
			if(StringUtils.isBlank(xeApplyNo)) {
				ExceptionHelper.thow("9999", "第三方订单编号为空");
			}
			
			queryStatusRequest.setXeApplyNo(xeApplyNo);
			preRequestUrl = XinHeHuiClient.preRequestUrl(XhhService.QUERY_APPROVE);
			preRequestParam = XinHeHuiClient.preRequestParam(queryStatusRequest);
		} catch (Exception e) {
			String[] ids = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					approveStatus, approveStatusName, null, timeAudit, null, thModeIDType, 
					queryStatusRequest, null, ThirdLogEventStatus.FAIL, 
					XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
			
			String thAuditDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thAuditDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FA_SONG_SHI_BAI, null, thModeIDType, 
					currentUserId, currentUserName, now);
			return false;
		}
//		==========================请求前:开始==================================
//		======================请求:开始===========================
		String requestJsonString = null;
		try {
			requestJsonString = XinHeHuiClient.request(preRequestUrl, preRequestParam);
		} catch (Exception e) {
			String[] ids = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					approveStatus, approveStatusName, null, timeAudit, null, thModeIDType, 
					queryStatusRequest, requestJsonString, ThirdLogEventStatus.FAIL, 
					XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
			
			String thAuditDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thAuditDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FAN_HUI_SHI_BAI, null, thModeIDType, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================请求:结束===========================
//		======================处理:开始===========================
		QueryApproveResponse queryApproveResponse = null;
		String approveMessage_ = "";
		String spouseApproveMessage_ = "";
		String approveMessage__ = "";
		String approveMessage___ = "";
		String approveMessage = "";
		Date currentAuditTime = null;
		Set<String> carManTypes = CollectionInitUtil.emptySet();
		try{
			queryApproveResponse = XinHeHuiClient.parseResponse(requestJsonString, QueryApproveResponse.class);
			if(null == queryApproveResponse) {
				throw new BasePartnerException(999, "返回的数据或编号为空");
			}
			approveStatus = queryApproveResponse.getApproveStatus();
			List<ApproveMessage> approveMessages = queryApproveResponse.getApproveMessage();
			if(CollectionUtils.isNotEmpty(approveMessages)) {
				for(ApproveMessage approveMessageItem : approveMessages) {
					Integer relationship = approveMessageItem.getRelationship();
					Integer approveType = approveMessageItem.getApproveType();
					Integer approve_status = approveMessageItem.getApprove_status();
					String result = approve_status == 1 ? ":通过" : ":不通过";
					String condition = approveMessageItem.getCondition();
					if(relationship != null && 6 == relationship){ //本人
						carManTypes.add("03");
						if(approveType != null && 1 == approveType) { //初审
							approveMessage_ += condition + result + ",";
						} else if(approveType != null && 2 == approveType) { //终审
							approveMessage__ += condition + result + ",";
						} else if(approveType != null && 3 == approveType){ //风险审核
							approveMessage___ += condition + result + ",";
						}
					} else if(relationship != null && 1 == relationship) { //配偶
						carManTypes.add("01");
						if(approveType != null && 1 == approveType) { //初审
							spouseApproveMessage_ += condition + result + ",";
						}
					}
					approveMessage += condition + result +","; //全部审核
				}
			}
			
			if(StringUtils.isNotEmpty(approveMessage_)) {
				approveMessage_ = approveMessage_.substring(0, approveMessage_.length() - 1);
			} else {
				approveMessage_ = "没有初审不过原因";
			}
			
			if(StringUtils.isNotEmpty(approveMessage__)) {
				approveMessage__ = approveMessage__.substring(0, approveMessage__.length() - 1);
			} else {
				approveMessage__ = "没有终审不过原因";
			}
			if(StringUtils.isNotEmpty(approveMessage___)) {
				approveMessage___ = approveMessage___.substring(0, approveMessage___.length() - 1);
			} else {
				approveMessage___ = "没有风险审核不过原因";
			}
			if(StringUtils.isNotEmpty(approveMessage)) {
				approveMessage = approveMessage.substring(0, approveMessage.length() - 1);
			} else {
				approveMessage = "没有审核不过原因";
			}
			
			Date firstApproveTime = queryApproveResponse.getFirstApproveTime();
			Date lastApproveTime = queryApproveResponse.getLastApproveTime();
			Date riskApproveTime = queryApproveResponse.getRiskApproveTime();
			
			approveStatusName = (String)CachedEnums.getValue(approveStatus, ThirdApproveStatus.class);
			Integer thirdBusiStatus = null;
			
//			审核状态：0-未审核 1-初审通过 2-初审不通过 3-终审通过 4-终审不通过 5-风险审核通过 6-风险审核不通过
			if(approveStatus == 0) {
//				thirdBusiStatus = ThirdBusiStatus.CHU_SHEN_ZHONG.getCode();
			} else if(approveStatus == 1) {
				currentAuditTime = firstApproveTime;
				thirdBusiStatus = ThirdBusiStatus.CHU_SHEN_TONG_GUO.getCode();
			} else if(approveStatus == 2) {
				currentAuditTime = firstApproveTime;
				thirdBusiStatus = ThirdBusiStatus.CHU_SHEN_BU_TONG_GUO.getCode();
			} else if(approveStatus == 3) {
				currentAuditTime = lastApproveTime;
				thirdBusiStatus = ThirdBusiStatus.ZHONG_SHEN_TONG_GUO.getCode();
			} else if(approveStatus == 4) {
				currentAuditTime = lastApproveTime;
				thirdBusiStatus = ThirdBusiStatus.ZHONG_SHEN_BU_TONG_GUO.getCode();
			}  else if(approveStatus == 5) {
				currentAuditTime = riskApproveTime;
				thirdBusiStatus = ThirdBusiStatus.FENG_XIAN_SHEN_PI_TONG_GUO.getCode();
			}  else if(approveStatus == 6) {
				currentAuditTime = riskApproveTime;
				thirdBusiStatus = ThirdBusiStatus.FENG_KONG_SHEN_PI_BU_TONG_GUO.getCode();
			} else {
				ExceptionHelper.thow("999", "审核状态不合法");
			}
			
				
//				如果结果是‘初审通过’，往“fk_待审批列表”表插一条模块id为“M_xhhzsys”(鑫合汇资审一审)的待审批信息；
//				将业务信息表的第三方渠道业务状态值更改为‘鑫合汇资审一审中’;
//				将第三方订单信息的第三方渠道业务状态值更改为‘鑫合汇资审一审中 （10.12调整）
			if(ThirdBusiStatus.CHU_SHEN_TONG_GUO.getCode().equals(thirdBusiStatus)) {
				YwBusiness ywBusinessDb = ywBusinessMapper.selectByPrimaryKey(busiId);
				
				if(null != ywBusinessDb) {
					//前提：风控完成（110）<= 业务状态 <= 500 ,并且 资金流程状态 <= 财务一审核中(100)。
					Integer busiStatusDb = ywBusinessDb.getBusiStatus();
					Integer addedStatus1Db = ywBusinessDb.getAddedStatus1();
					if(busiStatusDb >= BusiStatus.SHEN_PI_WAN_CHENG.getCode() && busiStatusDb <= BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode()
							&& addedStatus1Db <= AddedStatus1.CAI_WU_YI_SHEN_HE_ZHONG.getCode()) { 
						thirdBusiStatus = ThirdBusiStatus.XHH_ZI_SHEN_YI_SHEN_ZHONG.getCode();
						
						FkAuditList fkAuditList = new FkAuditList();
						fkAuditList.setDpStatus(DpStatus.NORMAL.getCode());
						fkAuditList.setModeId(ModeIDType.XHHZSYS.getCode());
						fkAuditList.setBusiId(busiId);
						int count = fkAuditListService.countRefined(fkAuditList);
						if(count == 0) {
//					fkAuditListService.deletedRefined(fkAuditList);
							fkAuditListService.insertFkAuditList(ywBusiness, ModeIDType.XHHZSYS, "鑫合汇初审查询成功", new AbstractSysUser() {
								@Override
								public String getName() {
									return currentUserName;
								}
								
								@Override
								public String getId() {
									return currentUserId;
								}
							});
						}
						try{
							String sqlXmls = "INSERT INTO `sys_log4j` VALUES ('"+UUIDFactory.getUUID()+"', '鑫合汇初审通过', '" + busiId + "', '业务状态："+busiStatusDb+"', '附加状态："+addedStatus1Db+"', '"+ DateUtil.dateTo14String(new Date())+"','','添加鑫合汇资审一审记录：" + count + "' ,0)";
					    	WhereSqlExt whereSqlExt = new WhereSqlExt();
			            	whereSqlExt.setWhereSql(sqlXmls);
			            	publicDao.insertWhereSql(whereSqlExt);
						} catch(Exception e) {
							
						}
					}
				}
				
			}
			
			if(CollectionUtils.isNotEmpty(carManTypes)) {
				String customerNo = thYwBusiness.getCustomerNo();
				String spouseName = thYwBusiness.getSpouseName();
				String spouseNo = thYwBusiness.getSpouseNo();
				for(String carManType : carManTypes) { //只可能01 03
					thCreditResultService.saveOrUpdateThCreditResult(busiId, busiType, xeApplyNo, 
							approveStatus, approveStatusName, 
							"01".equals(carManType) ? spouseName : customerName, 
									"01".equals(carManType) ? spouseNo : customerNo, carManType, 
											"01".equals(carManType) ? spouseApproveMessage_ : approveMessage_, currentUserId, currentUserName);
				}
			}
			
//			补充初审和终审审核，日记和履历
			if(logChuShen) {
				String[] ids_ = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
						ThirdApproveStatus.CHU_SHEN_TONG_GUO.getCode(), ThirdApproveStatus.CHU_SHEN_TONG_GUO.getValue(), 
						approveMessage_, firstApproveTime,  approveMessage_, ThirdModeIDType.CSCX, 
						queryStatusRequest, requestJsonString, ThirdLogEventStatus.SUCCESS, 
						XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
				String thAuditDataId = (null != ids_ && ids_.length >= 3) ? ids_[0] : null;
				thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, thAuditDataId, busiType, xeApplyNo, 
						ThirdApproveStatus.CHU_SHEN_TONG_GUO.getValue(), ThirdModeIDType.CSCX, currentUserId, currentUserName);
				
			}
			if(logZhongShen) {
				String[] ids__ = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
						ThirdApproveStatus.ZHONG_SHEN_TONG_GUO.getCode(), ThirdApproveStatus.ZHONG_SHEN_TONG_GUO.getValue(), 
						approveMessage__, lastApproveTime,  approveMessage__, ThirdModeIDType.ZHCX, 
						queryStatusRequest, requestJsonString, ThirdLogEventStatus.SUCCESS, 
						XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
				String thAuditDataId = (null != ids__ && ids__.length >= 3) ? ids__[0] : null;
				thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, thAuditDataId, busiType, xeApplyNo, 
						ThirdApproveStatus.ZHONG_SHEN_TONG_GUO.getValue(), ThirdModeIDType.ZHCX, currentUserId, currentUserName);
			}
			
			String[] ids = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					approveStatus, approveStatusName, approveMessage, currentAuditTime, approveMessage___, thModeIDType, 
					queryStatusRequest, requestJsonString, ThirdLogEventStatus.SUCCESS, 
					XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
			
			String thAuditDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, thAuditDataId, busiType, xeApplyNo, 
					approveStatusName, thModeIDType, currentUserId, currentUserName);
			
			YwBusiness ywBusiness_ = new YwBusiness();
			ywBusiness_.setId(busiId);
			ywBusiness_.initUpdateData(currentUserId, currentUserName);
			ywBusiness_.setThirdBusiStatus(thirdBusiStatus);
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness_);
			
			thYwBusiness.setId(thBusiDataId);
			thYwBusiness.initUpdateData(currentUserId, currentUserName);
			thYwBusiness.setThirdBusiStatus(thirdBusiStatus);
			thYwBusinessMapper.updateByPrimaryKeySelective(thYwBusiness);
			
			//鑫合汇征信查询结果提示
//			OtherMessageApp otherMessageApp_ = new OtherMessageApp();
//			otherMessageApp_.setModeId(thModeIDType.getCode());
//			otherMessageApp_.setBusiId(busiId);
//			otherMessageApp_.setDataid(thAuditDataId);
//			otherMessageApp_.setTypeMsg("01"); //01 提示 02 通知 03 预警
//			otherMessageApp_.setTypeMsgEvent(typeMsgEvent);
//			otherMessageApp_.setNotificationBar("客户" + customerName + "鑫合汇征信查询结果:" + approveStatusName);
//			otherMessageApp_.setTitle("客户" + customerName + "鑫合汇征信查询结果");
//			otherMessageApp_.setContent("反馈时间：" + DateUtil.dateTo12String(now) + "/n征信结果：" + approveStatusName);
//			otherMessageApp_.setTimeCreate(now);
//			otherMessageApp_.setTimeSend(now);
//			otherMessageApp_.setStatusMsg(MessageStatus.WEI_TUI_SONG.getCode());
//			
//			String shortMessage_ = "客户" + customerName +"鑫合汇征信查询结果：" + approveStatusName + "，详情请登录APP查看。";
//			serviceHelper.saveMsg(otherMessageApp_, salesmanId, customerName, shortMessage_, null, logger);
			systemService.diepuNewsHandle(new AbstractSysUser() {
				@Override
				public String getName() {
					return currentUserName;
				}
				
				@Override
				public String getId() {
					return currentUserId;
				}
			}, thModeIDType.getCode(), typeMsgEvent, busiId, null);
			
			return true;
		} catch (Exception e) {
			String[] ids = saveThAuditinfoAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					approveStatus, approveStatusName, approveMessage___, timeAudit, null, thModeIDType, 
					queryStatusRequest, requestJsonString, ThirdLogEventStatus.FAIL, 
					XhhService.QUERY_APPROVE_DES, currentUserId, currentUserName);
			
			String thAuditDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thAuditDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.CHU_LI_SHI_BAI, null, thModeIDType, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================处理:结束===========================	
	}
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public boolean saveSubmitXinHeHuiAudit(String busiId,String currentUserId, String currentUserName) {
		if(StringUtils.isBlank(busiId)) { //业务ID无，不需要记录错误处理（没意义）
			ExceptionHelper.thow("999", "业务记录ID不能为空");
		}
		Date now = new Date();
		YwBusinessDetail ywBusinessDetail = null;
		ApplyLastInstanceRequest applyLastInstanceRequest = null;
		String thBusiDataId = null;
		String xeApplyNo = null;
		
		String preRequestUrl = null;
		Map<String, String> preRequestParam = null;
		
		String busiType = "xhh";
		try {
			applyLastInstanceRequest = new ApplyLastInstanceRequest();
			
			ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(busiId);
			if(null == ywBusinessDetail) {
				ExceptionHelper.thow("999", "业务记录不存在或已被删除");
			}
			ywBusinessDetailMapper.mapper(ywBusinessDetail);
			
			YwBusinessBuyer ywBusinessBuyerParam = new YwBusinessBuyer();
			ywBusinessBuyerParam.setBusiId(busiId);
			ywBusinessBuyerParam.setCarManType("03"); //主借人
			ywBusinessBuyerParam.setDpStatus(DpStatus.NORMAL.getCode());
			YwBusinessBuyer zhuJieRen = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
			if(null == zhuJieRen) {
				ExceptionHelper.thow("999", "主借人记录不存在或已被删除");
			}
//			applyLastInstanceRequest.setName(zhuJieRen.getName());
			String sex = zhuJieRen.getSex();
			if(StringUtils.isNotBlank(sex)) {
				try{
					applyLastInstanceRequest.setSex(Integer.valueOf(sex));
				} catch (NumberFormatException e) {
					//解析性别出错
					logger.error("解析婚否出错:busiId:{},sex:{}.{}",busiId, sex, e);
				}
			}
			applyLastInstanceRequest.setSex(1);
			applyLastInstanceRequest.setRegister(zhuJieRen.getFamilyRegister());
//			applyLastInstanceRequest.setCardNo(zhuJieRen.getIdno());
			String education = zhuJieRen.getEducation();
			if(StringUtils.isNotBlank(education)) {
				try{
					applyLastInstanceRequest.setDegree(Integer.valueOf(education));
				} catch (NumberFormatException e) {
					//解析学历出错
					logger.error("解析婚否出错:busiId:{},education:{}.{}",busiId, education, e);
				}
			}
//			maritalStatus
			String maritalStatus = zhuJieRen.getMaritalStatus();
			if(StringUtils.isNotBlank(maritalStatus)) {
				try{
					applyLastInstanceRequest.setMaritalStatus(Integer.valueOf(maritalStatus));
				} catch (NumberFormatException e) {
					//解析婚否出错
					logger.error("解析婚否出错:busiId:{},maritalStatus:{}.{}",busiId, maritalStatus, e);
				}
			}
//			applyLastInstanceRequest.setMobile1(zhuJieRen.getTel1());
			applyLastInstanceRequest.setMobile2(zhuJieRen.getTel2());
			applyLastInstanceRequest.setLiveAddr(zhuJieRen.getNowAddr());
			applyLastInstanceRequest.setCompanyName(zhuJieRen.getCompany());
			String job = zhuJieRen.getJob();
			if(StringUtils.isNotBlank(job)) {
				try{
					applyLastInstanceRequest.setPosition(Integer.valueOf(job));
				} catch (NumberFormatException e) {
					//解析职位出错
					logger.error("解析职位出错:busiId:{},job:{}.{}",busiId, job, e);
				}
			}
			String monthIncome = zhuJieRen.getMonthIncome();
			if(StringUtils.isNotBlank(monthIncome)) {
				try{
					applyLastInstanceRequest.setMonthlyIncome(Double.valueOf(monthIncome));
				} catch (NumberFormatException e) {
					//解析收入出错
					logger.error("解析收入出错:busiId:{},monthIncome:{}.{}",busiId, monthIncome, e);
				}
			}
			
			ywBusinessBuyerParam.setCarManType("01");//配偶
			YwBusinessBuyer peiou = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
			if(null != peiou) {
//				applyLastInstanceRequest.setSpouseName(peiou.getName());
//				applyLastInstanceRequest.setSpouseCardNo(peiou.getIdno());
//				applyLastInstanceRequest.setSpouseMobile(peiou.getTel1());
				applyLastInstanceRequest.setSpouseCompanyName(peiou.getCompany());
				String peiouJob = peiou.getJob();
				if(StringUtils.isNotBlank(peiouJob)) {
					try{
						applyLastInstanceRequest.setSpousePosition(Integer.valueOf(peiouJob));
					} catch (NumberFormatException e) {
						//解析配偶职位出错
						logger.error("解析配偶职位出错:busiId:{},peiouJob:{}.{}",busiId, peiouJob, e);
					}
				}
				String peiouMonthIncome = peiou.getMonthIncome();
				if(StringUtils.isNotBlank(peiouMonthIncome)) {
					try{
						applyLastInstanceRequest.setSpouseMonthlyIncome(Double.valueOf(peiouMonthIncome));
					} catch (NumberFormatException e) {
						//解析配偶收入出错
						logger.error("解析配偶收入出错:busiId:{},peiouMonthIncome:{}.{}",busiId, peiouMonthIncome, e);
					}
				}
			}
			
			/*YwBusinessBuyerExt ywBusinessBuyerExtParam = new YwBusinessBuyerExt();
			ywBusinessBuyerExtParam.setBaseWhere();
			ywBusinessBuyerExtParam.setBusiId(busiId);
			ywBusinessBuyerExtParam.setCarManType("02"); //担保人
			List<YwBusinessBuyer> danbaorens = ywBusinessBuyerMapper.selectByExt(ywBusinessBuyerExtParam);
			if(CollectionUtils.isNotEmpty(danbaorens)) {
				List<SponsorInfo> sponsorInfos = CollectionInitUtil.emptyList();
				for(YwBusinessBuyer danbaoren : danbaorens) {
					SponsorInfo sponsorInfo = new SponsorInfo();
					sponsorInfo.setSponsorName(danbaoren.getName());
					String danbaorensex = danbaoren.getSex();
					if(StringUtils.isNotBlank(danbaorensex)) {
						try{
							sponsorInfo.setSponsorSex(Integer.valueOf(danbaorensex));
						} catch (NumberFormatException e) {
							//解析担保人性别出错
							logger.error("解析担保人性别出错:busiId:{},danbaorensex:{}.{}",busiId, danbaorensex, e);
						}
					}
					sponsorInfo.setSponsorRegister(danbaoren.getFamilyRegister());
					sponsorInfo.setSponsorCardNo(danbaoren.getIdno());
					String danbaorenEducation = danbaoren.getEducation();
					if(StringUtils.isNotBlank(danbaorenEducation)) {
						try{
							sponsorInfo.setSponsorDegree(Integer.valueOf(danbaorenEducation));
						} catch (NumberFormatException e) {
							//解析担保人学历出错
							logger.error("解析担保人学历出错:busiId:{},danbaorenEducation:{}.{}",busiId, danbaorenEducation, e);
						}
					}
					String danbaorenmaritalStatus = danbaoren.getMaritalStatus();
					if(StringUtils.isNotBlank(danbaorenmaritalStatus)) {
						try{
							sponsorInfo.setSponsorMaritalStatus(Integer.valueOf(danbaorenmaritalStatus));
						} catch (NumberFormatException e) {
							//解析担保人婚否出错
							logger.error("解析担保人婚否出错:busiId:{},danbaorenmaritalStatus:{}.{}",busiId, danbaorenmaritalStatus, e);
						}
					}
					sponsorInfo.setSponsorMobile1(danbaoren.getTel1());
					sponsorInfo.setSponsorMobile2(danbaoren.getTel2());
					sponsorInfo.setSponsorLiveAddr(danbaoren.getNowAddr());
					sponsorInfo.setSponsorCompanyName(danbaoren.getCompany());
					String danbaorenjob = danbaoren.getJob();
					if(StringUtils.isNotBlank(danbaorenjob)) {
						try{
							sponsorInfo.setSponsorPosition(Integer.valueOf(danbaorenjob));
						} catch (NumberFormatException e) {
							//解析担保人职务出错
							logger.error("解析担保人职务出错:busiId:{},danbaorenjob:{}.{}",busiId, danbaorenjob, e);
						}
					}
					String danbaorenmonthIncome = danbaoren.getMonthIncome();
					if(StringUtils.isNotBlank(danbaorenmonthIncome)) {
						try{
							sponsorInfo.setSponsorMonthlyIncome(Double.valueOf(danbaorenmonthIncome));
						} catch (NumberFormatException e) {
							//解析担保人月收入出错
							logger.error("解析担保人月收入出错:busiId:{},danbaorenmonthIncome:{}.{}",busiId, danbaorenmonthIncome, e);
						}
					}
					sponsorInfos.add(sponsorInfo);
				}
				applyLastInstanceRequest.setSponsorInfo(sponsorInfos);
			}*/
			
			applyLastInstanceRequest.setCarDealer(ywBusinessDetail.getDealerName());
			YwBusinessCar ywBusinessCar = new YwBusinessCar();
			ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessCar.setBusiId(busiId);
			ywBusinessCar = ywBusinessCarMapper.selectRefined(ywBusinessCar);
			if(null == ywBusinessCar) {
				ExceptionHelper.thow("999", "车辆记录不存在或已被删除");
			}
			applyLastInstanceRequest.setCarBrand(getCarBrand(ywBusinessCar.getNameCarBrand(), ywBusinessCar.getNameCarSeries(), ywBusinessCar.getNameCarModel()));
			applyLastInstanceRequest.setCarSeatNumber(ywBusinessCar.getSeatNum());
			String carType = ywBusinessCar.getCarType();
			if(StringUtils.isNotBlank(carType)) {
				try{
					applyLastInstanceRequest.setCarProperty(Integer.valueOf(carType));
				} catch (NumberFormatException e) {
					//解析车辆性质出错
					logger.error("解析车辆性质出错:busiId:{},carType:{}.{}",busiId, carType, e);
				}
			}
			YwBusinessLoan ywBusinessLoan = new YwBusinessLoan();
			ywBusinessLoan.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessLoan.setBusiId(busiId);
			ywBusinessLoan = ywBusinessLoanMapper.selectRefined(ywBusinessLoan);
			if(null == ywBusinessLoan) {
				ExceptionHelper.thow("999", "车贷记录不存在或已被删除");
			}
			if("01".equals(carType)) {
				applyLastInstanceRequest.setCarValue(ywBusinessLoan.getCarPrice());
			} else if("02".equals(carType)) {
				applyLastInstanceRequest.setCarValue(ywBusinessLoan.getCarEstimatePrice());
			}
			Double loanAmount = ywBusinessLoan.getLoanAmount();
			//向鑫合汇发送终审请求时，如果该订单的金额大于20w，直接在报文中将   垫款金额（同用款金融） 修改为20w。
			double maxLoanAmount = 200000;
			if(null == loanAmount) {
				loanAmount = 0d;
			}
			if(loanAmount > maxLoanAmount) {
				loanAmount = maxLoanAmount;
			}
//			applyLastInstanceRequest.setLoanAmount(ywBusinessLoan.getLoanAmount());
			applyLastInstanceRequest.setLoanAmount(loanAmount);
			applyLastInstanceRequest.setLoanTimeLimit(1);
			
			ThYwBusiness thYwBusinessParam = new ThYwBusiness();
			thYwBusinessParam.setBusiType(busiType);
			thYwBusinessParam.setDpStatus(DpStatus.NORMAL.getCode());
			thYwBusinessParam.setBusiId(busiId);
			ThYwBusiness thYwBusiness = thYwBusinessMapper.selectRefined(thYwBusinessParam);
			if(null == thYwBusiness) {
				ExceptionHelper.thow("9999", "第三方订单信息记录不存在或已被删除");
			}
			thBusiDataId = thYwBusiness.getId();
			xeApplyNo = thYwBusiness.getThirdId();
			if(StringUtils.isBlank(xeApplyNo)) {
				ExceptionHelper.thow("9999", "第三方订单编号为空");
			}
			applyLastInstanceRequest.setXeApplyNo(xeApplyNo);
			applyLastInstanceRequest.setLastInstanceStatus(1);//只有通过的才会提交终审
			
			preRequestUrl = XinHeHuiClient.preRequestUrl(XhhService.APPLY_LAST_INSTANCE);
			preRequestParam = XinHeHuiClient.preRequestParam(applyLastInstanceRequest);
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEvent(), 
					null, applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.APPLY_LAST_INSTANCE_DES, ThirdModeIDType.TJZS,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thBusiDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FA_SONG_SHI_BAI, null, ThirdModeIDType.TJZS, 
					currentUserId, currentUserName, now);
			return false;
		}
//		==========================请求前:开始==================================
//		======================请求:开始===========================
		String requestJsonString = null;
		try {
			requestJsonString = XinHeHuiClient.request(preRequestUrl, preRequestParam);
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEvent(), 
							requestJsonString, applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.APPLY_LAST_INSTANCE_DES, ThirdModeIDType.TJZS,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thBusiDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FAN_HUI_SHI_BAI, null, ThirdModeIDType.TJZS, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================请求:结束===========================
//		======================处理:开始===========================
		try{
			BasePartnerResponse basePartnerResponse = XinHeHuiClient.parseResponse(requestJsonString, BasePartnerResponse.class);
			if(null == basePartnerResponse) {
				//不影响
			}
			ThYwBusiness thYwBusiness = new ThYwBusiness();
			thYwBusiness.setId(thBusiDataId);
			thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.ZHONG_SHEN_ZHONG.getCode());
			thYwBusinessMapper.updateByPrimaryKeySelective(thYwBusiness);
			
			thLogsService.saveOrUpdateLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEvent(), 
							requestJsonString, applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.SUCCESS, XhhService.APPLY_LAST_INSTANCE_DES, ThirdModeIDType.TJZS,
					currentUserId, currentUserName);
			
			
			thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, thBusiDataId, busiType, xeApplyNo, 
					XhhService.APPLY_LAST_INSTANCE_DES, ThirdModeIDType.TJZS, currentUserId, currentUserName);
			

			YwBusiness ywBusiness= new YwBusiness();
			ywBusiness.setId(busiId);
			ywBusiness.setThirdBusiStatus(ThirdBusiStatus.ZHONG_SHEN_ZHONG.getCode());
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			return true;
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEvent(), 
							requestJsonString, applyLastInstanceRequest == null ? null : applyLastInstanceRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.APPLY_LAST_INSTANCE_DES, ThirdModeIDType.TJZS,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thBusiDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.CHU_LI_SHI_BAI, null, ThirdModeIDType.TJZS, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================处理:结束===========================		
	}
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public boolean saveQueryRepay(String busiId, 
			String currentUserId, String currentUserName) {
		if(StringUtils.isBlank(busiId)) { //业务ID无，不需要记录错误处理（没意义）
			ExceptionHelper.thow("999", "业务记录ID不能为空");
		}
		Date now = new Date();
		QueryStatusRequest queryStatusRequest = null;
		String xeApplyNo = null;
		String preRequestUrl = null;
		Map<String, String> preRequestParam = null;
		
		String busiType = "xhh";
		String thBusiDataId = null;
		Date repayDate = null;
		BigDecimal repayFee = null;
		Integer repayStatus = null;
		BigDecimal demandMarginFee = null;
		
		ThYwBusiness thYwBusiness = null;
		try {
			queryStatusRequest = new QueryStatusRequest();
			YwBusiness ywBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
			if(null == ywBusiness) {
				ExceptionHelper.thow("999", "业务记录不存在或已被删除");
			}
			ThYwBusiness thYwBusinessParam = new ThYwBusiness();
			thYwBusinessParam.setBusiType(busiType);
			thYwBusinessParam.setDpStatus(DpStatus.NORMAL.getCode());
			thYwBusinessParam.setBusiId(busiId);
			thYwBusiness = thYwBusinessMapper.selectRefined(thYwBusinessParam);
			if(null == thYwBusiness) {
				ExceptionHelper.thow("9999", "第三方订单信息记录不存在或已被删除");
			}
			thBusiDataId = thYwBusiness.getId();
			xeApplyNo = thYwBusiness.getThirdId();
			if(StringUtils.isBlank(xeApplyNo)) {
				ExceptionHelper.thow("9999", "第三方订单编号为空");
			}
			
			queryStatusRequest.setXeApplyNo(xeApplyNo);
			preRequestUrl = XinHeHuiClient.preRequestUrl(XhhService.QUERY_REPAY);
			preRequestParam = XinHeHuiClient.preRequestParam(queryStatusRequest);
		} catch (Exception e) {
			String[] ids = saveThInsteadPayListAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					ThirdModeIDType.DCZTCX, repayDate, repayFee, repayStatus, 
					demandMarginFee, queryStatusRequest, null, 
					ThirdLogEventStatus.FAIL, XhhService.QUERY_REPAY_DES, 
					currentUserId, currentUserName);
			
			String thInsteadPayListDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thInsteadPayListDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FA_SONG_SHI_BAI, null, ThirdModeIDType.DCZTCX, 
					currentUserId, currentUserName, now);
			return false;
		}

//		==========================请求前:开始==================================
//		======================请求:开始===========================
		String requestJsonString = null;
		try {
			requestJsonString = XinHeHuiClient.request(preRequestUrl, preRequestParam);
		} catch (Exception e) {
			String[] ids = saveThInsteadPayListAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					ThirdModeIDType.DCZTCX, repayDate, repayFee, repayStatus, 
					demandMarginFee, queryStatusRequest, requestJsonString, 
					ThirdLogEventStatus.FAIL, XhhService.QUERY_REPAY_DES, 
					currentUserId, currentUserName);
			
			String thInsteadPayListDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thInsteadPayListDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FAN_HUI_SHI_BAI, null, ThirdModeIDType.DCZTCX, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================请求:结束===========================
//		======================处理:开始===========================
		QueryRepayResponse queryRepayResponse = null;
		String recordName = null;
		try{
			queryRepayResponse = XinHeHuiClient.parseResponse(requestJsonString, QueryRepayResponse.class);
			if(queryRepayResponse == null) {
				throw new BasePartnerException(999, "返回的数据为空");
			}
			repayDate = queryRepayResponse.getRepayDate();
			String repayDate14 = DateUtil.dateTo14String(repayDate);
			repayFee = queryRepayResponse.getRepayFee();
			demandMarginFee = queryRepayResponse.getDemandMarginFee();
			repayStatus = queryRepayResponse.getRepayStatus();
//			0待还款 1正常还款成功 2代偿还款成功
			if(null != repayStatus) {
				if(0 == repayStatus) {
					recordName = "待还款(" + repayDate14 + ")";
				} else if(1 == repayStatus) {
					recordName = "正常还款成功(" + repayDate14 + ")";
				} else if(2 == repayStatus) {
					recordName = "代偿还款成功(" + repayDate14 + ")";
				}
			}
			String[] ids = saveThInsteadPayListAndLog(busiId, thBusiDataId, busiType, xeApplyNo, ThirdModeIDType.DCZTCX, 
					repayDate, repayFee, repayStatus, demandMarginFee, queryStatusRequest, requestJsonString,
					ThirdLogEventStatus.SUCCESS, XhhService.QUERY_REPAY_DES, currentUserId, currentUserName);
			
			String thInstendPayListDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			thBusinessRecordService.saveOrUpdateThBusinessRecord(busiId, thInstendPayListDataId, busiType, xeApplyNo, 
					recordName, ThirdModeIDType.DCZTCX, currentUserId, currentUserName);
			
			thYwBusiness.setId(thBusiDataId);
			thYwBusiness.setThirdCompensatoryStatus(repayStatus);
			thYwBusinessMapper.updateByPrimaryKeySelective(thYwBusiness);
			
			return true;
		} catch (Exception e) {
			String[] ids = saveThInsteadPayListAndLog(busiId, thBusiDataId, busiType, xeApplyNo, 
					ThirdModeIDType.DCZTCX, repayDate, repayFee, repayStatus, 
					demandMarginFee, queryStatusRequest, requestJsonString, 
					ThirdLogEventStatus.FAIL, XhhService.QUERY_REPAY_DES, 
					currentUserId, currentUserName);
			
			String thInsteadPayListDataId = (null != ids && ids.length >= 3) ? ids[0] : null;
			String logId = (null != ids && ids.length >= 3) ? ids[1] : null;
			String logSubId = (null != ids && ids.length >= 3) ? ids[2] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thInsteadPayListDataId, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.CHU_LI_SHI_BAI, null, ThirdModeIDType.DCZTCX, 
					currentUserId, currentUserName, now);
			return false;
		}
//		======================处理:结束===========================	
	}
	
	
//	=====================================辅助方法=============================================
	/**
	 * 保存合作伙伴业务和日记
	 * @author xiongxiaotun <br/>
	 * @Title saveLog  <br/>
	 * @Description 保存合作伙伴业务和日记  <br/>
	 * @param busiType
	 * @param busiId
	 * @param ywBusinessDetail
	 * @param thirdBusiStatus
	 * @param thirdCompensatoryStatus
	 * @param clientType
	 * @param applyLoanRequest
	 * @param thirdLogEventStatus
	 * @param describeEvent
	 * @param thModeIDType
	 * @param xeApplyNo
	 * @param salermanProvince
	 * @param currentUserId
	 * @param currentUserName
	 * @return String[0] thirdId, String[1] 日记ID, String[2] 子日记ID
	 * @version V1.0  <br/>
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 60)
	private String[] saveThBussinessAndLog(String busiType, String busiId, YwBusinessDetail ywBusinessDetail, ThirdBusiStatus thirdBusiStatus, 
			ThirdCompensatoryStatus thirdCompensatoryStatus, ClientType clientType, ApplyLoanRequest applyLoanRequest, String responseMessageEvent,
			ThirdLogEventStatus thirdLogEventStatus, String describeEvent, ThirdModeIDType thModeIDType,
			String xeApplyNo, String salermanProvince, String currentUserId, String currentUserName){
		ThYwBusiness thYwBusiness = thYwBusinessService.saveOrUpdateThYwBusiness(busiType, busiId, ywBusinessDetail, thirdBusiStatus, 
				thirdCompensatoryStatus, clientType, applyLoanRequest, xeApplyNo, salermanProvince, currentUserId, currentUserName);
		String dataId = thYwBusiness.getId();
		String[] logIds = thLogsService.saveOrUpdateLog(busiId, dataId, busiType, xeApplyNo, 
				applyLoanRequest == null ? null : applyLoanRequest.getRequestMessageEvent(), 
				responseMessageEvent, applyLoanRequest == null ? null : applyLoanRequest.getRequestMessageEventEncode(),
						thirdLogEventStatus, describeEvent, thModeIDType,
				currentUserId, currentUserName, JSON.toJSONString(thYwBusiness));
		String logId = (null != logIds && logIds.length >= 2) ? logIds[0] : null;
		String logSubId = (null != logIds && logIds.length >= 2) ? logIds[1] : null;
		return new String[] {dataId, logId, logSubId};
	}
	
	/**
	 * 保存合作伙伴第三方审批信息和日记
	 * @author xiongxiaotun <br/>
	 * @Title saveThAuditinfoAndLog  <br/>
	 * @Description 保存合作伙伴第三方审批信息和日记  <br/>
	 * @param busiId
	 * @param dataId
	 * @param busiType
	 * @param xeApplyNo
	 * @param approveStatus
	 * @param approveStatusName
	 * @param approveMessage
	 * @param timeAudit
	 * @param ccol1 审核不通过条件
	 * @param ThModeIDType
	 * @param queryStatusRequest
	 * @param responseMessageEvent
	 * @param thirdLogEventStatus
	 * @param describeEvent
	 * @param currentUserId
	 * @param currentUserName
	 * @return
	 * @version V1.0  <br/>
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 60)
	private String[] saveThAuditinfoAndLog(String busiId, String dataId,
			String busiType, String xeApplyNo, Integer approveStatus,
			String approveStatusName,String approveMessage, Date timeAudit, String ccol1,
			ThirdModeIDType ThModeIDType, QueryStatusRequest queryStatusRequest, String responseMessageEvent,
			ThirdLogEventStatus thirdLogEventStatus, String describeEvent, String currentUserId, String currentUserName){
		
		ThAuditinfo thAuditinfo = thAuditinfoService.saveOrUpdateThAuditinfo(busiId, dataId, busiType, xeApplyNo, approveStatus, approveStatusName, approveMessage,
				timeAudit, ThModeIDType, currentUserId, currentUserName);
		
		String[] logIds = thLogsService.saveOrUpdateLog(busiId, dataId, busiType, xeApplyNo, 
				queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
				responseMessageEvent, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
						thirdLogEventStatus, describeEvent, ThModeIDType,
				currentUserId, currentUserName);
		String logId = (null != logIds && logIds.length >= 2) ? logIds[0] : null;
		String logSubId = (null != logIds && logIds.length >= 2) ? logIds[1] : null;
		return new String[] {thAuditinfo.getId(), logId, logSubId};
	}
	
	/**
	 * 保存合作伙伴第三方代偿信息和日记
	 * @author xiongxiaotun <br/>
	 * @Title: saveThInsteadPayListAndLog  <br/>
	 * @Description: 保存合作伙伴第三方代偿信息和日记  <br/>
	 * @param busiId
	 * @param dataId
	 * @param busiType
	 * @param xeApplyNo
	 * @param thModeIDType
	 * @param repayDate
	 * @param repayFee
	 * @param repayStatus
	 * @param demandMarginFee
	 * @param queryStatusRequest
	 * @param responseMessageEvent
	 * @param thirdLogEventStatus
	 * @param describeEvent
	 * @param currentUserId
	 * @param currentUserName
	 * @return
	 * @version V1.0  <br/>
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 60)
	private String[] saveThInsteadPayListAndLog(String busiId, String dataId,
			String busiType, String xeApplyNo, ThirdModeIDType thModeIDType,
			Date repayDate, BigDecimal repayFee, Integer repayStatus, BigDecimal demandMarginFee, 
			QueryStatusRequest queryStatusRequest, String responseMessageEvent,
			ThirdLogEventStatus thirdLogEventStatus, String describeEvent, String currentUserId, String currentUserName){
		
		ThInsteadPayList thInsteadPayList = thInsteadPayListService.saveOrUpdateThInsteadPayList(busiId, 
				repayDate, repayFee, repayStatus, demandMarginFee, busiType, xeApplyNo, currentUserId, currentUserName);
		
		String[] logIds = thLogsService.saveOrUpdateLog(busiId, dataId, busiType, xeApplyNo, 
				queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
				responseMessageEvent, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
						thirdLogEventStatus, describeEvent, thModeIDType,
				currentUserId, currentUserName);
		String logId = (null != logIds && logIds.length >= 2) ? logIds[0] : null;
		String logSubId = (null != logIds && logIds.length >= 2) ? logIds[1] : null;
		return new String[] {thInsteadPayList.getId(), logId, logSubId};
	}
	
	/**
	 * 获取车品牌
	 * @param nameCarBrand
	 * @param nameCarSeries
	 * @param nameCarModel
	 * @return
	 */
	private static String getCarBrand(String nameCarBrand, String nameCarSeries, String nameCarModel){
		if(StringUtils.isNotBlank(nameCarModel)) {
			nameCarModel = nameCarModel.trim();
			if(StringUtils.isNotBlank(nameCarBrand) && nameCarModel.startsWith(nameCarBrand)) {
				nameCarModel = nameCarModel.substring(nameCarBrand.length() + 1);
			}
			if(StringUtils.isNotBlank(nameCarSeries) && nameCarModel.startsWith(nameCarSeries)) {
				nameCarModel = nameCarModel.substring(nameCarSeries.length() + 1);
			}
		}
		return (StringUtils.isNotBlank(nameCarBrand) ? nameCarBrand : "") + "," + 
				(StringUtils.isNotBlank(nameCarSeries) ? nameCarSeries : "") + "," +  
				(StringUtils.isNotBlank(nameCarModel) ? nameCarModel : "");
	}
}
